package cn.main.controller;

import cn.main.service.ColumnService;
import cn.main.web.SpringBean;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.Column;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: chengwei
 * Date:   2016/5/13
 * Time:   15:26
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {

    /**
     * 文件上传
     * @param req
     * @param resp
     * @return 文件上传后的数据信息
     * @throws Exception
     */
    @RequestMapping(value="/upload.do",produces =  "text/html;charset=UTF-8")
    @ResponseBody
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("开始");
        Map<String,Object> map = new HashMap<>();

        String path = req.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
//        String fileName = new Date().getTime()+".jpg";
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("fileUrl", req.getContextPath() + "/upload/");

        return JSONObject.fromObject(map).toString();
    }

    @RequestMapping("/download.do")
    public void download(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String encodedfileName = null;
        String agent = req.getHeader("USER-AGENT");
//        if(null != agent && -1 != agent.indexOf("MSIE")){//IE
//            encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
//        }else if(null != agent && -1 != agent.indexOf("Mozilla")){
            encodedfileName = new String ("帐号信息.txt".getBytes("UTF-8"),"iso-8859-1");
//        }else{
//            encodedfileName = java.net.URLEncoder.encode("帐号信息.txt","UTF-8");
//        }
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
        String path = req.getServletContext().getRealPath("upload");
        File file = new File(path,"帐号信息.txt");
        ServletOutputStream out = resp.getOutputStream();

        BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
        byte[] b = new byte[8192];
        int a;
        while ((a = input.read(b)) != -1) {
            out.write(b,0,a);
        }
        
    }

    /**
     * 统一转发接口
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping("/forward")
    public ModelAndView forward(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Map<String,Object> map =new HashMap<>();
        map.put("type",req.getParameter("type"));
        Map<String,Object> map1 =new HashMap<>();
        map1.put("d",map);
        return new ModelAndView("/upload/selectImages",map1);
    }

    /**
     * 统一转发接口
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping("/h")
    public void DoHttp(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        URL url = new URL("http://localhost:8082/file/forward");
        ColumnService service = SpringBean.getBean(ColumnService.class);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        con.connect();
        DataOutputStream out = new DataOutputStream(con
                .getOutputStream());
        out.writeBytes("type=txt&p=lll");
        out.flush();
        out.close();
        String len;
        BufferedReader stream = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
        resp.setContentType("text/html;charset=UTF-8");
        while (true) {
            len = stream.readLine();
            if (len == null ) {
                break;
            }
            resp.getWriter().print(len + "\n");
        }
        System.out.println(con.getContentEncoding());
        stream.close();
        con.disconnect();
//        return new ModelAndView("/upload/selectImages");
    }
}
